import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart' hide Action;
import 'package:www.znpigai.teacher/global_store/state.dart';
import 'package:www.znpigai.teacher/home_page/subject_tab_component/item/state.dart';
import 'package:www.znpigai.teacher/utils/http.dart';
import 'package:www.znpigai.teacher/utils/nav.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'state.dart';

Effect<SubjectListState> buildEffect() {
  return combineEffects(<Object, Effect<SubjectListState>>{
    Lifecycle.initState: _onInit,
    SubjectListAction.onLoad: _onLoad,
    SubjectListAction.onReload: _onReload,
    SubjectListAction.onDelete: _onDelete,
    SubjectListAction.onCreate: _onCreate,
  });
}

void _onInit(Action action, Context<SubjectListState> ctx) async {
  if (ctx.state.items.length == 0) {
    _onReload(action, ctx);
  }
}

void _onReload(Action action, Context<SubjectListState> ctx) async {
  if (ctx.state.isLoading) {
    return;
  }

  if (action.payload != null) {
    action.payload(); // callback
  }

  _getSubject(action, ctx, GlobalState.firstPageIndex, GlobalState.pageSize);
}

void _onLoad(Action action, Context<SubjectListState> ctx) async {
  var pageIndex = ctx.state.pageIndex;
  var total = ctx.state.pageTotal;
  var isLoading = ctx.state.isLoading;
  if (pageIndex >= total || isLoading) {
    return;
  }

  _getSubject(action, ctx, pageIndex, GlobalState.pageSize);
}

void _onCreate(Action action, Context<SubjectListState> ctx) async {
  Navigator.of(ctx.context).pushNamed(Nav.SUBJECT_EDIT).then((ret) {
    if (ret != null) {
      _onReload(action, ctx);
    }
  });
}

void _onDelete(Action action, Context<SubjectListState> ctx) async {
  bool ok = await Util.showConfirmDialog('删除', '确定要删除？', ctx.context);
  if (!ok) {
    return;
  }

  ctx.dispatch(SubjectListActionCreator.loading(ctx.state.self));
  int index = action.payload;
  var item = ctx.state.items[index];
  var url = "/correct/pub/api/exercises/del.mvc";
  final query = {'id': item.id};
  var result = await Http.get(url, query: query);

  ctx.dispatch(SubjectListActionCreator.loaded(ctx.state.self));
  if (result.success) {
    ctx.dispatch(SubjectListActionCreator.deleted(ctx.state.self, index));
  } else {
    Util.alertFail(result, ctx.context);
  }
}

void _getSubject(Action action, Context<SubjectListState> ctx, int pageIndex,
    int pageSize) async {
  ctx.dispatch(SubjectListActionCreator.loading(ctx.state.self));

  var url = "/correct/teacher/api/homework/entrepot/list.mvc";
  final query = {
    'grade': ctx.state.grade,
    'type': ctx.state.type,
    'tag': ctx.state.tag,
    'theme': ctx.state.theme,
    'keyword': ctx.state.keyword,
    'self': ctx.state.self,
    'cpage': pageIndex,
    'psize': pageSize,
  };
  var result = await Http.get(url, query: query);

  ctx.dispatch(SubjectListActionCreator.loaded(ctx.state.self));
  if (result.success) {
    var responseList = result.data['items'];
    var pageTotal =
        (result.data['total'] / GlobalState.pageSize).ceil(); // 向上取整

    pageIndex += 1;
    List<SubjectState> items = new List();
    if (responseList != null) {
      responseList.forEach((item) {
        try {
          SubjectState cellData = new SubjectState.fromJson(item);
          cellData.self = ctx.state.self;
          items.add(cellData);
        } catch (e) {
          // No specified type, handles all
          print(e);
        }
      });
    }

    ctx.dispatch(SubjectListActionCreator.listResult(
        ctx.state.self, items, pageTotal, pageIndex));
  } else {
    Util.alertFail(result, ctx.context);
  }
}
